package ie.dcu.spca.util;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;

import android.util.Base64;
import android.util.Log;

/**
 * Send Data Utils
 * 
 * @author wpc
 * 
 */
public class DataSendUtils {

    public static boolean httpPost(String pathToOurFile, String urlServer,
            String formName) {

        HttpURLConnection connection = null;
        DataOutputStream outputStream = null;

        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";

        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1 * 1024 * 1024;

        boolean sendSuccess = true;

        try {
            FileInputStream fileInputStream = new FileInputStream(new File(
                    pathToOurFile));

            URL url = new URL(urlServer);
            connection = (HttpURLConnection) url.openConnection();

            // Allow Inputs & Outputs
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setUseCaches(false);

            // Enable POST method
            connection.setRequestMethod("POST");

            connection.setRequestProperty("Connection", "Keep-Alive");
            connection.setRequestProperty("Content-Type",
                    "multipart/form-data;boundary=" + boundary);

            outputStream = new DataOutputStream(connection.getOutputStream());
            outputStream.writeBytes(twoHyphens + boundary + lineEnd);
            outputStream.flush();
            outputStream.writeBytes("Content-Disposition: form-data; name=\""
                    + formName + "\";filename=\"" + pathToOurFile + "\""
                    + lineEnd);
            outputStream.flush();
            outputStream.writeBytes(lineEnd);
            outputStream.flush();

            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            buffer = new byte[bufferSize];

            // Read file
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);

            while (bytesRead > 0) {
                outputStream.write(buffer, 0, bufferSize);
                outputStream.flush();
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);
            }

            outputStream.writeBytes(lineEnd);
            outputStream.flush();
            outputStream.writeBytes(twoHyphens + boundary + twoHyphens
                    + lineEnd);
            outputStream.flush();
            fileInputStream.close();
            outputStream.close();

            connection.getResponseCode();
            connection.getResponseMessage();

        } catch (Exception ex) {
            sendSuccess = false;
        } finally {
            connection.disconnect();
        }
        return sendSuccess;
    }

    /**
     * TODO FIX Check the file length, it's long not int.This may lead the
     * problem.
     * 
     * @param fileName
     * @param url
     * @return
     */
    public static boolean httpPostBase64(String fileName, String url,
            String formKey, String inputName) {
        try {
            File file = new File(fileName);
            FileInputStream in = new FileInputStream(file);
            byte[] buffer = new byte[(int) file.length() + 100];
            int length = in.read(buffer);
            String data = Base64.encodeToString(buffer, 0, length,
                    Base64.DEFAULT);

            HttpPost httpRequest = new HttpPost(url);

            /*
             * NameValuePair实现请求参数的封装
             */
            List<NameValuePair> params = new LinkedList<NameValuePair>();
            params.add(new BasicNameValuePair("hl", "en_GB"));
            params.add(new BasicNameValuePair("formkey", formKey));
            params.add(new BasicNameValuePair(inputName, data));

            /* 添加请求参数到请求对象 */
            httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
            /* 发送请求并等待响应 */
            HttpResponse httpResponse = new DefaultHttpClient()
                    .execute(httpRequest);
            /* 若状态码为200 ok */
            if (httpResponse.getStatusLine().getStatusCode() != 200) {
                Log.d("HTTP Response:",url);
                Log.d("HTTP Response Code", httpResponse.getStatusLine().toString());
                return false;
            }

        } catch (Exception e) {
            for (StackTraceElement s : e.getStackTrace())
                Log.d("Exception", s.toString());
            Log.d("Exception", e.getCause().toString());
            Log.d("Exception", e.getLocalizedMessage());

            return false;
        }

        return true;
    }
}
